package com.xumingxun.aibox.domain.node;

import com.xumingxun.aibox.context.Context;
import com.xumingxun.aibox.domain.condition.Branch;
import com.xumingxun.aibox.domain.var.Var;
import com.xumingxun.aibox.enums.BoolEnum;
import com.xumingxun.aibox.enums.NodeTypeEnum;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Getter
@Setter
@Accessors(chain = true)
public class BranchNode extends Node{

    List<Branch> branches=new ArrayList<>();

    public BranchNode(Context context) {
        super(context);

        init();
    }

    @Override
    public void init() {
        this.type = NodeTypeEnum.BRANCH;
        this.export = false;
        this.nodeName = "Branch Node";
        this.exportVars.add(new Var(this.nodeName,"branch_name","分支名称"));

        //初始化IF和ELSE分支
        Branch ifBranch=new Branch();
        ifBranch.setName("IF");
        ifBranch.setBool(BoolEnum.AND);
        this.branches.add(ifBranch);

        Branch elseBranch=new Branch();
        elseBranch.setName("ELSE");
        elseBranch.setBool(BoolEnum.AND);
        this.branches.add(elseBranch);

    }

    public Branch getBranch(String branchName){
        List<Branch> branches1=branches.stream().filter(item->item.getName().equals(branchName)).collect(Collectors.toList());
        if(!branches1.isEmpty()){
            return branches1.get(0);
        }
        return null;
    }

    public void setNextNode(Branch branch,Node nextNode) {
        List<Branch> branches1=branches.stream().filter(item->item.getName().equals(branch.getName())).collect(Collectors.toList());
        if(!branches1.isEmpty()) {
            branches1.get(0).setNode(nextNode);
        }
    }

    @Override
    public void setNextNode(Node nextNode) {
        throw new RuntimeException("BranchNode cannot set next node directly");
    }

    public Node execute() {
        Branch elseBranch=null;
        for (Branch branch : branches) {
            if(branch.getName().equals("ELSE")){
                elseBranch=branch;
                continue;
            }
            if (branch.execute(context)) {
                return branch.getNode();
            }
        }

        return elseBranch.getNode();
    }

    @Override
    public String getResult(){
        return null;
    }

    public NodeTypeEnum getType() {
        return NodeTypeEnum.BRANCH;
    }

}
